package com.only4play.common.handler;

import com.only4play.common.constants.ErrorCodeEnum;
import com.only4play.common.exception.ApplicationException;
import com.only4play.common.exception.ValidationException;
import com.only4play.common.model.GeneralResponse;
import com.only4play.common.model.ValidateResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * ApplicationExceptionHandler
 *
 * @author liyuncong
 * @date 2023/11/20 16:04
 **/
@Slf4j
@RestControllerAdvice
public class ApplicationExceptionHandler {

    @ExceptionHandler(value = {Exception.class, Throwable.class})
    public GeneralResponse<?> handlerException(Exception exception) {
        Integer code = ErrorCodeEnum.SERVER_ERROR.getCode();
        String message = ErrorCodeEnum.SERVER_ERROR.getMessage();
        Object payload = null;

        if (exception instanceof ApplicationException) {
            code = ((ApplicationException) exception).getErrorCodeEnum().getCode();
            message = exception.getMessage();
            payload = ((ApplicationException) exception).getData();
            log.error("[全局异常拦截] ApplicationException: errorCode=[{}], errorMessage=[{}]", code, message);
        } else if (exception instanceof ValidationException) {
            code = ErrorCodeEnum.PARAM_ILLEGAL.getCode();
            message = ErrorCodeEnum.PARAM_ILLEGAL.getMessage();
            List<ValidateResult> result = ((ValidationException) exception).getResult();

            String validateResultJson = "";
            if (!CollectionUtils.isEmpty(result)) {
                StringBuilder jsonBuild = new StringBuilder(result.size());
                for (ValidateResult validateResult : result) {
                    jsonBuild.append("{").append(validateResult.name()).append(" : ").append(validateResult.message()).append("} ");
                }
                validateResultJson = jsonBuild.toString();
            }

            log.error("[全局异常拦截] ValidationException: errorCode=[{}], errorMessage=[{}], validateResult=[{}]",
                code, message, validateResultJson, exception);
            payload = result;
        } else {
            log.error("[全局异常拦截] Exception: errorMessage=[{}]", exception.getMessage(), exception);
        }

        // return json message
        return GeneralResponse.of(code, message, payload);
    }
}
